package com.rockcent.mall.lib.repository;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rockcent.common.common.SQLObjectDoing;
import com.rockcent.mall.lib.domain.Banner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

/**
 * Created by zhangjh on 2016/11/14.
 */
@Repository
public class BannerRepositoryImpl implements BannerRepositoryCustom {
    private static final Logger log = LoggerFactory.getLogger(BannerRepositoryImpl.class);

    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public Banner findBannerAbout(Integer seqNo, Long mallId, String direction) {

        SQLObjectDoing<Banner> result = (sql, fields, params, typeReferenceMap) -> {
            sql.append("SELECT %s FROM banner b" +
                    "  WHERE b.`is_delete`='NO' and b.`mall_id` = :mallId");
            if (direction.equals(Banner.UP)) {
                sql.append(" AND b.`seq_no` < :seqNo order by `seq_no` desc limit 1");
            }
            if (direction.equals(Banner.DOWN)) {
                sql.append(" AND b.`seq_no` > :seqNo order by `seq_no` asc limit 1");
            }
            params.put("mallId", mallId);
            params.put("seqNo", seqNo);
            fields.append("b.*");
            log.debug(sql.toString());
        };
        return result.go(Banner.class, jdbcTemplate, log, objectMapper);
    }


}
